import React from "react";
import { sleep } from 'antd-mobile/es/utils/sleep';
import styles from '@/assets/css/guest.module.css';
import type guest from "@/types/guest.ts";
import type business from "@/types/business";

const Index = () => {
  // 用户数据
  const [business] = useState<business>(React.business);
  // 列表数据
  const [list, SetList] = useState<guest[]>([]);
  // 加载状态
  const [HasMore, SetHasMore] = useState<boolean>(true);
  // 当前页
  const [page, SetPage] = useState<number>(1);
  // 当前列表长度
  const [ListCount, SetListCount] = useState<number>(0);
  // 右滑组件
  const SwipeActionRef = useRef();
  // 右滑按钮样式
  const RightBtn = [
    {
      key: 'delete',
      text: '删除住客',
      color: 'danger',
    }
  ];

  // 下拉刷新
  const OnRefresh = async () => {
    await sleep(1000);
    SetList([]);
    SetPage(1);
    SetHasMore(true);
  }

  // 上拉加载
  const OnLoadMore = async () => {
    await sleep(1000);
    await GetGuestData();
  }

  const GetGuestData = async () => {
    // 组装参数
    const params = {
      page,
      busid: business.id
    }
    // 发起请求
    const result = await React.Http.post('/guest/index', params);
    // 处理请求结果
    if (result.code === 1) {
      // 获取数据总数
      const count = result.data.count ?? 0;
      // 把新的数据和旧数据合并
      SetList(v => {
        const list = [...v, ...result.data.list];
        SetListCount(v => v + list.length);
        return list;
      })
      // 停止条件
      if (count === ListCount) {
        SetHasMore(false);
        return;
      }
      // 继续加载
      SetHasMore(true);
      SetPage(page => page + 1);
    } else {
      // 加载完成
      SetHasMore(false);
      React.fail(result.msg);
    }
  }

  // 删除事件
  const OnDelete = (id: number, index: number) => {
    React.UI.Dialog.confirm({
      title: "删除住客",
      content: "是否确认删除该住客？",
      onConfirm: async () => {
        // 组装参数
        const params = {
          id,
          busid: business.id
        };
        // 发起请求
        const result = await React.Http.post("/guest/del", params);
        if (result.code === 1) {
          React.success(result.msg, () => {
            // 无刷新静态删除
            SetList(prevList => {
              // 这里的 "_" 是一个占位符，因为我不需要操作数组的每一项，所以不需要第一个参数，我只需要使用索引来作比较
              const newList = prevList.filter((_, i) => i !== index);
              // const newList = prevList.slice(index, 1);
              SetListCount(newList.length); // 更新列表长度
              // 返回一个新列表，排除被删除的项
              return newList;
            });
          });
        } else {
          React.fail(result.msg);
        }
      }
    })
  }

  return (
    <>
      <React.UI.PullToRefresh onRefresh={OnRefresh}>
        {/* 列表结构 */}
        <React.UI.List>
          {list.map((item: guest, key: number) => (
            <React.UI.SwipeAction
              ref={SwipeActionRef}
              key={item.id}
              rightActions={RightBtn}
              onAction={() => OnDelete(item.id, key)}
            >
              <React.UI.List.Item
                key={item.id}
                description={item.mobile}
                onClick={() => React.navigate(`/guest/edit?gid=${item.id}`)}
              >
                {item.nickname}({item.gender_text})
              </React.UI.List.Item>
            </React.UI.SwipeAction>
          ))}
        </React.UI.List>

        {/* 上拉加载 */}
        <React.UI.InfiniteScroll
          loadMore={OnLoadMore}
          hasMore={HasMore}
          threshold={0}
        />
      </React.UI.PullToRefresh>

      <div className={styles.AddGuest}>
        <Link to="/guest/add">添加住客</Link>
      </div>
    </>
  )
}

export default Index;